(function(window, angular, undefined) {
	'use strict';
	angular.module('mainApp', [
		'ngResource',
		'ngRoute',
		'kingServices',
		'kingDirectives',
		'kingFilters',
		'reportControllers'
	])

	//配置路由
	.config(['$routeProvider', '$logProvider',
			function($routeProvider, $logProvider) {
				$routeProvider
                    .when('/report/main', {
                        templateUrl: '/js/apps/main/tpl/overview.html?v=20170313',
                        controller: 'overviewCtrl'
                    })
                    .when('/report/basicActive/:product', {
                        templateUrl: '/js/apps/main/tpl/basic_active.html?v=20170215',
                        controller: 'basicActiveCtrl'
                    })
                    .when('/report/basicTrend/:product', {
                        templateUrl: '/js/apps/main/tpl/basic_trend.html?v=20170215',
                        controller: 'basicTrendCtrl'
                    })
                    .when('/report/usersTerminal', {
                        templateUrl: '/js/apps/main/tpl/users_terminal.html?v=20170310',
                        controller: 'usersTerminalCtrl'
                    })
                    .when('/report/companyRank', {
                        redirectTo: '/report/companyRank/heZuoBan'
                    })
                    .when('/report/companyRank/:product', {
                        templateUrl: '/js/apps/main/tpl/company_rank.html?v=20170310',
                        controller: 'companyRankCtrl'
                    })
                    .when('/report/usersTerritory', {
                        templateUrl: '/js/apps/main/tpl/users_territory.html?v=20170310',
                        controller: 'usersTerritoryCtrl'
                    })
                    .when('/report/retention', {
                        redirectTo: '/report/retention/heZuoBan'
                    })
                    .when('/report/retention/:product', {
                        templateUrl: '/js/apps/main/tpl/retention.html?v=20170313_1',
                        controller: 'retentionCtrl'
                    })
					.otherwise({
						redirectTo: '/report/main'
					});
				$logProvider.debugEnabled(true);
			}
		])
        // 后台退出后，前端将无法获取到数据。此时应跳转到登录页。
	    .config(['$httpProvider', function($httpProvider){
            function getLastTime() {
                var localTime = t
                var otherTime = parseInt($.cookie('lastAjaxTime') || 0)
                return otherTime > localTime ? otherTime : localTime
            }
            function setLastTime(time) {
                t = time
                $.cookie('lastAjaxTime', time, {path: '/'})
            }
            function getNow(){
                return + new Date()
            }
            function back() {
                window.location = '/index.php/Login/logout'
            }
            function check(){
                // 当前时间与上次请求时间大于x分钟，则判断为已超时
                var now = getNow()
                var lastTime = getLastTime()
                setLastTime(now)
                if(now - lastTime >= 1800000)
                    back()
            }
            
            var t = getNow()
            setLastTime(t)
            $httpProvider.interceptors.push(function(){
                return {
                    request: function (request) {
                        check()
                        return request;
                    }
                }
            })
        }])
		.run(['$rootScope', '$http', '$timeout',
			function($rootScope, $http, $timeout) {
				if(/*@cc_on!@*/false){
					$rootScope.isIE = true;
				}
				else if(!!window.ActiveXObject || "ActiveXObject" in window){
					$rootScope.isIE = true;
				}
				// firstLogin在登录时设置，用于区分登录与刷新
				if($.cookie('firstLogin') == 1){
				    $rootScope.firstLogin = true
				    $.cookie('firstLogin', '', {path: '/'})
				}
				var app = $rootScope.app = {};
			}
		])
		.controller('mainCtrl', ['$scope', '$rootScope', '$location', function($scope, $rootScope, $location) {
            $rootScope.products = [
                {key: 'duLiBan', name: 'TimeOn独立版'},
                {key: 'heZuoBan', name: 'TimeOn合作版'},
                {key: 'yunShaDu', name: 'TimeOn云杀毒'},
                {key: 'yunBeiFen', name: 'TimeOn云备份'}
            ]
            var paths = $location.path().split('/')
            $rootScope.currentPage = paths[2]
			$rootScope.currentProduct = paths[3] || $rootScope.products[1].key // 默认合作版
            $rootScope.currentTime = paths[4]
            paths = null
            $rootScope.buttonCondition = {
                time: {
                    conditions: {
                        'basicActive': 1,
                        'basicTrend': 1,
                        'retention': 1
                    }
                },
                products: {
                    conditions: {
                        'basicActive': 1,
                        'basicTrend': 1,
                        'retention': 1,
                        'companyRank': 1
                    }
                }
            }
            $rootScope.$watch('currentProduct', function(newValue, oldValue){
                if(newValue && $rootScope.currentPage in $rootScope.buttonCondition.products.conditions){
                    // 应该考虑使用$routeParams
                    var paths = $location.path().split('/')
                    paths[3] = newValue
                    $location.path(paths.join('/'))
                }
            })
            $scope.getCurrentProductName = function(){
                var result
                $.each($rootScope.products, function(index, product){
                    if($rootScope.currentProduct === product.key) {
                        result = product
                        return false;
                    }
                })
                if(!result)
                    result = {key: undefined, name: '产品列表'}
                return result
            }
            $scope.changeProduct = function(product){
                $rootScope.currentProduct = product.key
            }
            
			var vm = $scope.vm = {}
			vm.menu = [
			    {
			        key: 'main', // key用来填充currentProduct
			        head: {text: '数据概览'},
			        url: function(){
			            var str = '/report/main'
			            return str
			        }
			    },
			    {
			        head: {text: '基本指标'},
			        children: [
			            {
			                key: 'basicActive',
			                text: '活跃用户',
			                url: function(){
			                    var str = '/report/basicActive'
			                    return str + '/' + $rootScope.currentProduct
			                }
			            },    
			            {
			                key: 'basicTrend',
			                text: '趋势分析',
                            url: function(){
                                var str = '/report/basicTrend'
                                return str + '/' + $rootScope.currentProduct
                            }
                        },
			            {
			                key: 'retention',
			                text: '留存统计',
                            url: function(){
                                var str = '/report/retention'
                                return str + '/' + $rootScope.currentProduct
                            }
                        }
			        ]
			    },
                {
                    head: {text: '用户分析'},
                    children: [
                        {
                            key: 'companyRank',
                            text: '企业排行',
                            url: function(){
                                var str = '/report/companyRank'
                                return str + '/' + $rootScope.currentProduct
                            }
                        },
                        {
                            key: 'usersTerritory',
                            text: '地域分布',
                            url: '/report/usersTerritory'
                        },
                        {
                            key: 'usersTerminal',
                            text: '终端情况',
                            url: '/report/usersTerminal'
                        }
                    ]
                }
			]
			void function(){
    			function isCurrent(obj){
    			    return obj.key === $rootScope.currentPage
    			}
    			function activate(obj){
    			    obj.active = true
    			}
    			$.each(vm.menu, function(index, obj) {
    			    var breakEach = false
    			    if(obj.children){
    			        $.each(obj.children, function(i, child){
    			            if(isCurrent(child)){
    			                activate(child)
    			                breakEach = true
    			                return false;
    			            }
    			        })
    			    } else {
    			        breakEach = isCurrent(obj)
    			    }
    			    if(breakEach){
    			        activate(obj)
    			        return false;
    			    }
    			})
			}()
			
            $rootScope.intervalCalendar = {
                begin: {
                    dateStr: '',
                    calendar: null
                },
                end: {
                    dateStr: '',
                    calendar: null
                }
            }
            void function($scope){
                var obj = {
                    pageType: {
                        duLiBan: 'timeon',
                        heZuoBan: 'timeoneqq',
                        yunShaDu: 'cloud',
                        yunBeiFen: 'backup'
                    },
                    baseType: {
                        date: 'dayActive',
                        week: 'weekActive',
                        month: 'monthActive'
                    }
                }
                $scope.converter = function(type, key){
                    var value = obj[type] && obj[type][key]
                    return value ? value : key
                }
            }($scope)
		}])
        .controller('viewCtrl', ['$scope', '$rootScope',function($scope, $rootScope) {
            
        }])
        .directive('dropGroup', function(){
            return {
                restrict: 'CA',
                link: function(scope, elem, attrs){
                    var obj = scope.buttonCondition
                    obj.time.elem = elem.find('.time')
                    obj.products.elem = elem.find('.products')
                    scope.$watch('currentPage', function(newValue, oldValue){
                        $.each(obj, function(i, button){
                            button.elem[
                                newValue in button.conditions 
                                    ? 'show'
                                    : 'hide'
                            ]()
                        })
                    })
                }
            }
        })
        .factory('gotoAnchor', ['$location', '$anchorScroll', function($location, $anchorScroll){
            return function (id) {
                var old = $location.hash()
                $location.hash(id);
                $anchorScroll();
                $location.hash(old)
            }
        }])
})(window, window.angular);